/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package bean.session;

import entity.ContactEntity;
import entity.PersonEntity;
import entity.SystemUserEntity;
import java.util.List;
import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.Root;

/**
 *
 * @author wei
 */
@Stateless
public class PersonEntityFacade extends AbstractFacade<PersonEntity> {

    @PersistenceContext(unitName = "MacTeam-warPU")
    private EntityManager em;
    
    @EJB
    ContactEntityFacade contactFacade;

    protected EntityManager getEntityManager() {
        return em;
    }

    public PersonEntityFacade() {
        super(PersonEntity.class);
    }

    public PersonEntity getPersonByName(String userName) {
        CriteriaBuilder builder = getEntityManager().getCriteriaBuilder();
        javax.persistence.criteria.CriteriaQuery cq = builder.createQuery();
        Root<PersonEntity> dataObjectRoot = cq.from(PersonEntity.class);
        cq.select(dataObjectRoot);
        cq.where(builder.equal(dataObjectRoot.get("name"), userName));

        return (PersonEntity) getEntityManager().createQuery(cq).getSingleResult();
    }
    
    public PersonEntity getPersonByContact(ContactEntity contact) {
        CriteriaBuilder builder = getEntityManager().getCriteriaBuilder();
        javax.persistence.criteria.CriteriaQuery cq = builder.createQuery();
        Root<PersonEntity> dataObjectRoot = cq.from(PersonEntity.class);
        cq.select(dataObjectRoot);
        cq.where(builder.equal(dataObjectRoot.get("contact"), contact));

        return (PersonEntity) getEntityManager().createQuery(cq).getSingleResult();
    }
    
    public PersonEntity getPersonByEmail(String email) {
        ContactEntity contact = contactFacade.getContactByEmail(email);
        return getPersonByContact(contact);
    }

    public boolean checkUserNameExist(String userName) {

        try {
            getPersonByName(userName);
        } catch (NoResultException e) {
            return false;
        } catch (Exception ex) {
            return true;
        }

        return true;
    }

    //TODO: we need to get lockedPerson instead of just sys user
    public List<SystemUserEntity> getLockedUser() {
        Query query = (Query) em.createQuery("Select s from SystemUser s WHERE s.locked=true");
        List<SystemUserEntity> list = (List<SystemUserEntity>) query.getResultList();
        return list;
    }
}
